<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/23
 * Time: 10:15
 */

namespace zhtfrontend\controllers;

use common\components\services\message\ManualWechatMessage;
use common\models\datas\Customer;
use common\models\datas\SalesMechanic;
use zhtfrontend\components\bases\BaseController;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\BadRequestHttpException;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\widgets\ActiveForm;

class MechanicsalesController extends BaseController
{
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = SalesMechanic::find()->where(['site_id' => Fun::getSiteId()])->orderBy('id DESC');
        if ($param['searchData']) {
            $search_data = $param['searchData'];
            if (!empty($search_data['name'])) {
                $cids = Customer::find()->select('id')->where(['like', 'name', $search_data['name']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                $data->andWhere(['customer_id' => $cids]);
            }
            if (isset($search_data['status']) && $search_data['status'] != null) {
                $data->andWhere(['status' => $search_data['status']]);
            }
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['operate', 'customer_name', 'mobile', 'user_name']);

        return $this->render('index', ['data' => $array, 'pages' => $pages]);
    }

    public function actionUpdate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = SalesMechanic::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'update';
        if ($model->status == 0) {
            $model->status = 1;
            $items = [1 => '处理中', 2 => '加盟成功', 3 => '加盟失败'];
        } else {
            $items = [2 => '加盟成功', 3 => '加盟失败'];
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->user_id = \Yii::$app->user->id;
            $model->updated_at = time();
            $title = '推荐处理';
            $mechanic_name = $model->mechanic_name;
            if ($model->save(false)) {
                $m = '';
                $delay = 1;
                if ($model->status > 0) {
                    $str = "推荐机构：" . $mechanic_name . "\n处理状态：";
                    if ($model->status == 1) {
                        $str .= "处理中 \n";
                    } elseif ($model->status == 2) {
                        $str .= "推荐成功！\n";
                    } elseif ($model->status == 3) {
                        $str .= "推荐失败 \n";
                    }
                    if (!empty($model->remark)) {
                        $str .= "描述：" . $model->remark;
                    }
                    $res = (new ManualWechatMessage([
                        'customer_id' => $model->customer_id,
                        'title' => $title,
                        'desc' => $str,
                        'url' => '/recommendmechanic/list?site_id=' . Fun::getSiteId(),
                        'site_id' => Fun::getSiteId()
                    ]))->send();

                    if ($res > 0) {
                        $m = '--微信消息发送失败请电话联系';
                        $delay = 5;
                    }

                }
                return $this->redirectMessage('处理成功' . $m, Fun::url(['mechanicsales/index'], false, [], '', 'success', $delay));
            }
        }
        return $this->render('update', ['model' => $model, 'items' => $items]);
    }


}